<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <!-- <el-form-item label="姓名" prop="partnerId">
        <el-input v-model="dataForm.partnerId" placeholder="姓名"></el-input>
      </el-form-item>-->
      <!-- <el-form-item label="姓名" prop="partnerName">
        <el-input v-model="dataForm.partnerName" placeholder="姓名"></el-input>
      </el-form-item> -->
      <el-form-item label="心愿名称" prop="title">
        <el-input v-model="dataForm.title" placeholder="心愿名称"></el-input>
      </el-form-item>
      <el-form-item label="心愿缩略图" prop="wishInfo">
        <img :src="dataForm.wishInfo" v-if="dataForm.id" style="width: 40px;height: 40px;">
        <img :src="dataForm.wishInfo" v-if="!dataForm.id" style="width: 40px;height: 40px;">
        <el-upload
          class="upload-demo"
          :action="url"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="wishSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="心愿描述 " prop="detail">
        <el-input v-model="dataForm.detail" placeholder="心愿描述 "></el-input>
      </el-form-item>

      <el-form-item label="心愿状态" prop="wishStatus" v-if="!dataForm.id==true">
        <el-radio v-model="dataForm.wishStatus" label="1">进行中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="2">帮助中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="3">已完成</el-radio>
        <!-- <el-radio v-model="dataForm.wishStatus" label="4">暂停状态</el-radio> -->
        <el-radio v-model="dataForm.wishStatus" label="0">新建状态</el-radio>
      </el-form-item>
      <el-form-item label="心愿状态" prop="wishStatus" v-if="dataForm.id&&dataForm.wishStatus=='2'">
        <el-radio v-model="dataForm.wishStatus" label="1" :disabled="dataForm.wishStatus=='2'">进行中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="2" :disabled="dataForm.wishStatus=='2'">帮助中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="3" >已完成</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="0" :disabled="dataForm.wishStatus=='2'">新建状态</el-radio>
      </el-form-item>
      <el-form-item label="心愿状态" prop="wishStatus" v-if="dataForm.id&&dataForm.wishStatus=='3'">
        <el-radio v-model="dataForm.wishStatus" label="1" :disabled="dataForm.wishStatus=='3'">进行中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="2" :disabled="dataForm.wishStatus=='3'">帮助中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="3" :disabled="dataForm.wishStatus=='3'">已完成</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="0" :disabled="dataForm.wishStatus=='3'">新建状态</el-radio>
      </el-form-item>
      <el-form-item label="心愿状态" prop="wishStatus" v-if="dataForm.id&&dataForm.wishStatus=='1'">
        <el-radio v-model="dataForm.wishStatus" label="1" >进行中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="2" >帮助中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="3" >已完成</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="0" :disabled="dataForm.wishStatus=='1'">新建状态</el-radio>
      </el-form-item>
      <el-form-item label="心愿状态" prop="wishStatus" v-if="dataForm.id&&dataForm.wishStatus=='0'">
        <el-radio v-model="dataForm.wishStatus" label="1" >进行中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="2" >帮助中</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="3" >已完成</el-radio>
        <el-radio v-model="dataForm.wishStatus" label="0" >新建状态</el-radio>
      </el-form-item>
      <el-form-item label="所需学分" prop="targetCredit" v-if="!dataForm.id==true">
        <el-input v-model.number="dataForm.targetCredit" placeholder="所需学分" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="所需学分" prop="targetCredit" v-else>
        <el-input v-model="dataForm.targetCredit" placeholder="所需学分"  :disabled="dataForm.wishStatus!=='1'"></el-input>
      </el-form-item>
      <el-form-item label="已捐学分" prop="donateCredit" v-if="dataForm.id">
        <el-input v-model="dataForm.donateCredit"   placeholder="已捐学分" disabled></el-input>
      </el-form-item>
      <el-form-item label="申请理由" prop="whyUrl">
        <img :src="dataForm.whyUrl" v-if="dataForm.id" style="width: 40px;height: 40px;">
        <img :src="dataForm.whyUrl" v-if="!dataForm.id" style="width: 40px;height: 40px;">
        <el-upload
          class="upload-demo"
          :action="wishurl"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="支教老师" prop="teacherId">
        <el-select  v-model="dataForm.teacherId" placeholder="请选择" >
          <el-option
            v-for="item in projectList"
            :key="item.teacherId"
            :label="item.name"
            :value="item.teacherId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="推荐理由 " prop="teacherWhy">
        <el-input v-model="dataForm.teacherWhy" placeholder="推荐理由 "></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        // 避免重复提交
        formLock: true,
        visible: false,
        dataForm: {
          id: 0,
          partnerId: "",
          partnerName:'',
          teacherId: "",
          teacherWhy: "",
          title: "",
          detail: "",
          whyUrl: "",
          targetCredit: "",
          wishStatus: "1",
          wishFinInfo: "",
          gmtCreated: "",
          gmtUpdate: "",
          isAlive: "1",
          wishInfo:'',
          donateCredit:'',
        },
        dataRule: {
          // partnerName:[
          //      { required: true, message: "姓名不能为空", trigger: "blur" }
          // ],
          teacherId: [
            { required: true, message: "推荐老师不能为空", trigger: "blur" },

          ],
          teacherWhy: [
            { required: true, message: "推荐理由 不能为空", trigger: "blur" },
            { max: 80, message: "最长80个字符", trigger: "blur" }
          ],
          title: [
            { required: true, message: "心愿标题不能为空", trigger: "blur" },
            { max: 15, message: "最长15个字符", trigger: "blur" }
          ],
          detail: [
            { required: true, message: "心愿描述不能为空", trigger: "blur" },
            { max: 15, message: "最长15个字符", trigger: "blur" }
          ],
          targetCredit: [
            { required: true, message: "积分不能为空", trigger: "blur" }
          ]
        },
        url: "",
        wishurl:'',
        projectList:[],
      };
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/partner/partnerwish/upload?token=${this.$cookie.get("token")}`
      );
      this.wishurl = this.$http.adornUrl(
        `/partner/partnerwish/upload?token=${this.$cookie.get("token")}`
      );
      this.$http({
        url: this.$http.adornUrl(`/partner/teacherinfo/search`),
        method: "get",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        // console.log(data)
        if (data && data.code === 0) {
          this.projectList = data.list;
        }
      });
    },
    methods: {
      init(data) {
        this.dataForm.id = data.id || 0;
        if (data.partnerId) {
          this.dataForm.partnerId = data.partnerId;
          // alert(bookId)
        }
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/partner/partnerwish/info/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.dataForm.partnerId = data.partnerWish.partnerId;
                this.dataForm.teacherId = data.partnerWish.teacherId;
                this.dataForm.teacherWhy = data.partnerWish.teacherWhy;
                this.dataForm.title = data.partnerWish.title;
                this.dataForm.detail = data.partnerWish.detail;
                this.dataForm.wishInfo = data.partnerWish.wishInfo;
                this.dataForm.whyUrl = data.partnerWish.whyUrl;
                this.dataForm.targetCredit = data.partnerWish.targetCredit;
                this.dataForm.wishStatus = data.partnerWish.wishStatus + "";
                this.dataForm.isAlive = data.partnerWish.isAlive + "";
                this.dataForm.partnerName = data.partnerWish.partnerName;
                this.dataForm.donateCredit = data.partnerWish.donateCredit;
              }
            });
          }
        });
      },
      handleAvatarSuccess(response, file, fileList) {
        this.fileList = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.whyUrl = response.url;
        } else {
          this.$message.error(response.msg);
        }
      },
      wishSuccess(response, file, fileList) {
        this.fileList = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.wishInfo = response.url;
        } else {
          this.$message.error(response.msg);
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/png';
        if (!isJPG) {
          this.$message.error("上传封面只能是 png 格式!");
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 240;
          let height = 240;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width && img.height == height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的心愿缩略图必须是240*240!");
            return Promise.reject();
          }
        );
        return isJPG  && isSize;
      },
      beforeUpload(file) {
        const isJPG = file.type === 'image/png';
        if (!isJPG) {
          this.$message.error("上传封面只能是 png 格式!");
        }
        const isSize = new Promise(function(resolve, reject) {
          let width = 1029;
          // let height = 160;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.onload = function() {
            let valid = img.width == width ;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的心愿缩略图的宽度必须是1029!");
            return Promise.reject();
          }
        );
        return isJPG  && isSize;
      },
      // 表单提交
      dataFormSubmit() {
        if(this.formLock) {
          this.formLock = false
          this.$refs["dataForm"].validate(valid => {
            if (valid) {
              this.$http({
                url: this.$http.adornUrl(
                  `/partner/partnerwish/${!this.dataForm.id ? "save" : "update"}`
                ),
                method: "post",
                data: this.$http.adornData({
                  id: this.dataForm.id || undefined,
                  partnerId:this.dataForm.partnerId,
                  teacherId: this.dataForm.teacherId,
                  teacherWhy: this.dataForm.teacherWhy,
                  title: this.dataForm.title,
                  detail: this.dataForm.detail,
                  whyUrl: this.dataForm.whyUrl,
                  targetCredit: this.dataForm.targetCredit,
                  wishStatus: this.dataForm.wishStatus,
                  isAlive: this.dataForm.isAlive,
                  wishInfo:this.dataForm.wishInfo,
                  wishFinInfo:'-1',
                })
              }).then(({ data }) => {
                if (data && data.code === 0) {
                  this.$message({
                    message: "操作成功",
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                      this.visible = false
                      this.$emit("refreshDataList",this.dataForm.partnerId);
                      setTimeout(()=>{
                        this.formLock = true
                      }, 500)
                    }
                  });
                } else {
                  this.$message.error(data.msg);
                }
              });
            }
          });
        }
      }
    }
  };
</script>
